﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Ninject;
using MIMSDomain.Abstract;
using Ninject.Syntax;
using MIMSWeb.Infrastructure.Abstract;
using MIMSWeb.Infrastructure.Concrete;
using MIMSDomain.Entities;
using MIMSDomain.Concrete;
using MIMSCore.Logging;
using MIMSCore.Abstract;

namespace MIMSWeb.Infrastructure
{
    public class NinjectDependencyResolver : IDependencyResolver, IDisposable
    {
        private IKernel ninjectKernel;

        public IBindingToSyntax<T> Bind<T>()
        {
            return ninjectKernel.Bind<T>();
        }

        public IKernel Kernel
        {
            get
            {
                return ninjectKernel;
            }
        }
        
        public NinjectDependencyResolver()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }

        #region IDependencyResolver Members

        public object GetService(Type serviceType)
        {
            return ninjectKernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return ninjectKernel.GetAll(serviceType);
        }

        #endregion

        private void AddBindings()
        {
            ninjectKernel.Bind<IRepository<Patient>>().To<EFPatientRepository>();
            ninjectKernel.Bind<IRepository<MedicalPersonnel>>().To<EFMedicalPersonnelRepository>();
            ninjectKernel.Bind<IRepository<MedicalFacility>>().To<EFMedicalFacilityRepository>();
            ninjectKernel.Bind<IRepository<DrugHistory>>().To<EFDrugHistoryRepository>();
            ninjectKernel.Bind<ILogger<SynkronLogger>>().To<SynkronLogger>().WithConstructorArgument("category", "MIMSWeb");
            ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                ninjectKernel.Dispose();
            }
        }
    }
}